#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <cstdio>

using namespace std;

void setNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl failed");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "set " << fd << " NonBlock success" << endl;
}

int main()
{
    char buffer[1024];
    setNonBlock(0); // 标准输入设置阻塞等待
    sleep(1);

    while (1)
    {
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "echo: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            // 不是出错而是等待读事件就绪
            if (errno == EWOULDBLOCK)
            {
                cout << "0 read is not ready,try again" << endl; 
                sleep(1);
            }
            else
            {
                cout << "read failed,n = " << n << " ,errno:" << errno << " ,err string:" << strerror(errno) << endl;
                break;
            }

            // break;
        }
    }
    return 0;
}